package edu.office.jwt;


import edu.office.tools.PublicFields;
import io.smallrye.jwt.build.Jwt;
import jakarta.annotation.security.PermitAll;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import edu.office.tools.UserWithName;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;


@Path("/login")
@ApplicationScoped
public class EduOfficeJWT {
    @Inject
    CheckLogin checkLogin;
    @Path("/myLogin")
    @POST
    @PermitAll
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    public Response getJwt(User4Login user) {
        UserWithName userWithName=checkLogin.isUserlegal(user);
        if (userWithName.isValid()) {
            //把角色名称和登录名，以及姓和名加上
           Set<String> roles=new HashSet<>(
                   Arrays.asList(String.valueOf("l:"+user.getRoleId()),"m:"+user.getName(),"n:"+userWithName.getSecondName(),"o:"+userWithName.getFirstName(),"p:"+userWithName.getHashValue())
           );
           //把roles内容加密后，再放入Group，以免被滥用信息

            //
            String jwt= Jwt.issuer(PublicFields.myJWTIssue)
                    .subject(PublicFields.myJWTSubject)
                    .groups(roles)
                    .expiresAt(
                            System.currentTimeMillis()+3600
                    ).sign();
            String username="#;"+userWithName.getSecondName()+" "+userWithName.getFirstName();
            return Response.ok(jwt+username).build();
        } else {
            //System.out.println("Error");
            return Response.ok("Error").build();
        }
    }
}
